package java8;

import org.junit.Test;

import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.*;

/**
 * 流API
 *
 * @Author: zhenzhong.wang@honeywell.com
 * @Date: 2019/1/21 9:38 AM
 */
public class StreamTest {

  @Test
  public void testOne() {

    // 基本数据类型有三种Stream, IntStream, LongStream, DoubleStream
    IntStream a;
    LongStream b;
    DoubleStream c;

    Stream<Integer> stream1 = Stream.of(1, 2, 3);
    String[] array = new String[]{"a", "b", "c"};
    Stream<String> stream2 = Stream.of(array);
    System.out.println("=========print1");
    stream1.forEach(e -> {
      System.out.println(e);
    });

    // map 它的作用就是把 input Stream 的每一个元素，映射成 output Stream 的另外一个元素。
    stream2.map(String::toUpperCase).collect(Collectors.toList());
    System.out.println("=========print2");
    IntStream.of(1, 2, 3)
        .map(n -> n * n)
        .map(e -> {
              return e - 1;
            }
        )
        .forEach(e -> {
          System.out.println(e);
        });

    // 每一个stream只能被用一次，此处会报异常
//    stream1.map(n -> {
//      return n * n;
//    });


    Stream<List<Integer>> arrStream = Stream.of(
        Arrays.asList(1),
        Arrays.asList(2, 3),
        Arrays.asList(4, 5, 6)
    );
    System.out.println("=========print3");
    // flatMap处理一对多关系，将三个list处理结果合成一个Stream
    arrStream
        .flatMap(childList -> childList.stream())
        .forEach(e -> {
          System.out.println(e);
        });
    System.out.println("=========print4");
    IntStream.of(1,2,3,4,5,6,7,8).filter(n->n%2==0).forEach(e -> System.out.println(e));
  }
}
